<template>
  <div>
    <div>
      <el-tree

        ref="tree"
        :data="permissionList"
        show-checkbox
        default-expand-all
        node-key="id"
        check-strictly
        :props="defaultProps"
        @node-click="handleNodeClick"
      />
    </div>

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
        <el-button size="small" @click="cancelButton">取 消</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { transTree } from '@/utils/index'
import { getRoleId, assignPerm } from '@/api/setting'

export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      permissionList: [], // 权限列表数据
      defaultProps: {
        label: 'name',
        children: 'children'
      }
    }
  },
  created() {
    // 获取权限列表
    this.getPermissionList()
    // 获取id
    this.getRoleId()
  },
  methods: {
    // 获取id
    async getRoleId() {
      const res = await getRoleId(this.roleId)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    //   console.log(res)
    },
    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionList()
      this.permissionList = transTree(res.data, '0')

    //   console.log(res)
    },
    handleNodeClick() {},
    // 取消按钮
    cancelButton() {
      this.$emit('close')
    },

    // 设置权限按钮
    async setRolesBtn() {
      // Element 组件提供的获取勾选节点的方法
      const permIds = this.$refs.tree.getCheckedKeys()
      //   传入id 和permIds
      const res = await assignPerm({
        id: this.roleId,
        permIds
      })
      //   成功提示
      this.$message.success(res.message)
      //   向父元素请求 关闭弹窗
      this.$emit('close')
    //   console.log(res)
    //   console.log(permIds)
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
